 var MOVE_TYPE={};
MOVE_TYPE.next='后';
MOVE_TYPE.prev='前';
MOVE_TYPE.inner='下一级';
var tree_config={
    openRank:3
}
//当前选中的节点对象，通过click事件不断复写
var currentNode;
var setting = {
    view: {
        autoCancelSelected: false,
        txtSelectedEnable: true
    },
    edit:{
        enable: true,
        showRemoveBtn: false,
        showRenameBtn: false
    },
    data: {
        key: {
            name: systemZtree.keyName ? systemZtree.keyName : "name"
        },
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: 0
        }
    },
    callback:{
        onClick:function(event, treeId, treeNode){
            var id = treeNode.id;
            if(treeNode.level == 0){
                currentNode = null;
                $('#inputForm').hide();
                return ;
            }
            currentNode = treeNode;
            $.ajax({
                url: systemZtree.preUrl + '/info/' + id,
                type: "get",
                dataType: "json",
                success: function (data) {
                    if(data.success){
                        var entity = data.data;

                        $('#inputForm :text,select,input[type=hidden]').each(function(){
                            if(entity[this.name] != undefined){
                                this.value = entity[this.name];
                            }
                        });


                        $('#inputForm').attr('action', systemZtree.preUrl + '/update').show();
                    }
                }
            });
        },
        beforeDrop:function(treeId, treeNodes, targetNode, moveType) {
            if(targetNode.id == 0 && moveType != 'inner'){
                return false;
            }
            var msg = '确认将节点【' + treeNodes[0].name + '】移动到节点【' + targetNode.name + '】' + MOVE_TYPE[moveType] + '吗？';
            return confirm(msg);
        },
        onDrop:function(event, treeId, treeNodes, targetNode, moveType) {
            $('#inputForm').hide();
            var node = treeNodes[0];
            var parentNode = node.getParentNode();
            var nodeList = getNodeList(node);
            var nextNode = node.getNextNode();
            var preNode = node.getPreNode();
            if(nextNode && nextNode.sortNum){
                nodeList[0].sortNum=nextNode.sortNum-1;
            }else if(preNode && preNode.sortNum){
                nodeList[0].sortNum=preNode.sortNum - 0 +1;
            }
            $.ajax({
                type:"POST",
                url:systemZtree.preUrl + '/batchUpdate',
                dataType:"json",
                contentType:"application/json",
                data:JSON.stringify(nodeList),
                success:function(res){

                }
            });
        }
    }

};

function getNodeList(node){
    var arr = [];
    arr.push({id:node.id, rank:node.level, parentId:node.getParentNode().id});
    if(node.children && node.children.length > 0){
        $.each(node.children, function(i, item){
            arr = arr.concat(getNodeList(item));
        });
    }
    return arr;
}

$(document).ready(function(e) {
    $("#inputForm").hide();
    var options = {
        rules:systemZtree.rules,
        submitHandler:function(form){
            $(form).ajaxSubmit({
                type:'post',
                dataType:'json',
                success:function(data){
                    if(data){
                        layer.alert(data.msg,function(index){
                            layer.close(index);
                            window.location.reload();
                        });
                    }

                }
            });
        }
    };
    $("#inputForm").validate(options);
    $('#deleteButton').on('click', function(){
        layer.confirm("确定要删除该节点吗？其下子节点将一并删除！", function(index) {
            layer.close(index);
            var parent = currentNode.getParentNode();
            $.ajax({
                url: systemZtree.preUrl + '/delete/'+currentNode.id,
                type: "DELETE",
                dataType: "json",
                success: function (data) {
                    window.location.reload();
                }
            });
        });// end confirm

    });//end delete

    $('#addButton').on('click', function(){
        var nodes = zTree.getSelectedNodes();
        if(nodes && nodes.length == 1){
            $('#inputForm input[type=text],input[type=hidden]').each(function(){
                this.value = '';
            });
            $('#parentId').val(nodes[0].id);
            var node = nodes[0];
            var maxNum = -1;
            if(node.isParent && node.children){
                $.each(node.children, function(i, item){
                    if(item.sortNum - maxNum  > 0){
                        maxNum = item.sortNum;
                    }
                });
            }
            var maxNum = maxNum > 0 ? maxNum*1+1 : node.level*100 + 10;
            $('input[name=sortNum]').val(maxNum);
            $('#rank').val(node.level + 1);
            $('#inputForm').attr('action', systemZtree.preUrl + '/save').show();
            if(systemZtree.onAddBtnClick){
                systemZtree.onAddBtnClick(node);
            }
        }else{
            layer.alert('请先选择一个父节点');
        }
    });

    $.ajax({
        url: systemZtree.preUrl + '/queryForTree',
        type: "get",
        dataType: "json",
        success: function (res) {
            var rootData = {'id':0,'name':'根节点',sortNum:0};
            if(systemZtree.keyName){
                rootData[systemZtree.keyName]='根节点';
            }
            zNodes = [rootData];
            if(res.data && res.data.length > 0){
                zNodes = zNodes.concat(res.data);
            }

            var openRank = tree_config.openRank;
            if(systemZtree.openRank){
                openRank = systemZtree.openRank;
            }
            $.each(zNodes, function(i, n){
                if(n.rank == undefined || n.rank < openRank){
                    n.open=true;
                }
            });
//                console.log('nodes', zNodes, setting);
            zTree = $.fn.zTree.init($("#treeDiv"), setting, zNodes);
        }
    });
});


